﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom;
using System.Reflection;
using Ebc.DesignerDsl.CustomCode;
using Microsoft.VisualStudio.Modeling;
using Ebc.DesignerDsl.TypeBrowserIntegration;

namespace Ebc.DesignerDsl
{
    public partial class ExistingPart
    {
        private TypeDefinition partType;

        public TypeDefinition GetPartTypeValue()
        {
            if (this.partType == null)
            {
                this.partType = new TypeDefinition
                (
                    value =>
                    {
                        using (Transaction t = this.Store.TransactionManager.BeginTransaction("Change model"))
                        {
                            this.CSharpTypeString = value;
                            t.Commit();
                        }
                    },
                    value =>
                    {
                        using (Transaction t = this.Store.TransactionManager.BeginTransaction("Change model"))
                        {
                            this.ClrTypeString = value;
                            t.Commit();
                        }
                    },
                    () => this.CSharpTypeString,
                    usingNamespace =>
                    {
                        if (!this.Board.Usings.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Contains(usingNamespace))
                        {
                            using (Transaction t = this.Store.TransactionManager.BeginTransaction("Change model"))
                            {
                                this.Board.Usings += (Environment.NewLine + usingNamespace);

                                while (this.Board.Usings.StartsWith("\n") || this.Board.Usings.StartsWith(" ") || this.Board.Usings.StartsWith("\r"))
                                {
                                    this.Board.Usings = this.Board.Usings.Substring(1);
                                }

                                t.Commit();
                            }
                        }
                    }
                );

                if (string.IsNullOrEmpty(this.ClrTypeString))
                {
                    this.partType.SetType(typeof(object));
                }
            }

            return this.partType;
        }

        public string GetPartTypeNameValue()
        {
            return this.CSharpTypeString;
        }
    }
}